package com.liu.webstore.controller;

import com.liu.webstore.common.Constant;
import com.liu.webstore.entity.Event;
import com.liu.webstore.entity.User;
import com.liu.webstore.event.EventProducer;
import com.liu.webstore.service.LikeService;
import com.liu.webstore.util.HostHolder;
import com.liu.webstore.util.WebstoreUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author LiuYumei
 * @Date 2022/8/3 23:21
 */
@Controller
public class LikeController {
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    /**
     * 异步请求
     * entityType：1（帖子） 2（评论）
     */
    @PostMapping("/like")
    @ResponseBody
    public String getLike(int entityType, int entityId, int entityUserId, int postId) {
        User user = hostHolder.getUser();
        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        // 数量
        Long entityLikeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 状态
        Integer entityLikeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", entityLikeCount);
        map.put("likeStatus", entityLikeStatus);
        // 触发点赞事件
        if (entityLikeStatus == 1) {
            Event event = new Event()
                    .setTopic(Constant.TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }
        return WebstoreUtil.getJsonString(200, null, map);
    }
}
